import { Injectable } from '@nestjs/common';
import { CreateBorrowDto } from './dto/create-borrow.dto';
import { UpdateBorrowDto } from './dto/update-borrow.dto';
import { Borrow } from './entities/borrow.entity';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { getPageResult } from 'src/utils';
import { Book } from '../books/entities/book.entity';
import { Category } from '../category/entities/category.entity';
import * as moment from "moment";
@Injectable()
export class BorrowService {
  constructor(
    @InjectRepository(Borrow)
    private borrowRepository: Repository<Borrow>
  ) {}
  // 借书
  async create(createBorrowDto: CreateBorrowDto) {
    // return await this.borrowRepository.manager.transaction( async (transactionalEntityManager) => {
    //   await transactionalEntityManager.save(createBorrowDto);
    // })
    return await this.borrowRepository.insert(createBorrowDto);
  }
  // 借阅记录
  async findAll({pageIndex, pageSize, card_id, user_name}) {
    let queryBuilder = this.borrowRepository.createQueryBuilder('borrow')
    .leftJoinAndSelect(Book, 'book', 'book.id = borrow.book_id')
    .leftJoinAndSelect(Category, 'category', 'category.id = borrow.category_id')
    .select('book.book_name,category.category_name,borrow.*')
    .where('1=1')
    if(card_id) {
      queryBuilder = queryBuilder
      .andWhere('borrow.card_id = :card_id', { card_id: card_id })
    }
    if(user_name) {
      queryBuilder = queryBuilder
      .andWhere('borrow.user_name LIKE :user_name', { user_name: `%${user_name}%`})
    }
    return await getPageResult(pageIndex, pageSize, queryBuilder)
  }
  // 查看记录详情
  async findOne(id: number) {
    return await this.borrowRepository.createQueryBuilder('borrow')
    .leftJoinAndSelect(Book, 'book', 'book.id = borrow.book_id')
    .leftJoinAndSelect(Category, 'category', 'category.id = borrow.category_id')
    .select('book.*,category.category_name,borrow.*')
    .where({id})
  }
  // 归还图书
  async returnBorrow(id: number) {
    return await this.borrowRepository.update(id, { status: 1, actual_return_date: moment(Date.now()).format('YYYY-MM-DD hh:mm:ss') });
  }
  // 修改记录
  async update(id: number, updateBorrowDto: UpdateBorrowDto) {
    return await this.borrowRepository.update(id, updateBorrowDto);
  }
  // 删除记录
  async remove(id: number) {
    return await this.borrowRepository.softDelete(id);
  }
}
